package com.wyh.service.serviceImpl.feemanagementserviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyh.domain.dto.feemanagementdto.BillVerificationDto;
import com.wyh.domain.po.feemanagementpo.*;
import com.wyh.domain.vo.feemanagementvo.BillDetailsVos;
import com.wyh.mapper.feemanagementmapper.*;
import com.wyh.service.feemanagementservice.BillVerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.*;


@Service
@Transactional
public class BillVerificationServiceImpl extends ServiceImpl<BillVerificationMapper, Billes> implements BillVerificationService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private BillDetailVerificationMapper billDetailVerificationMapper;
    @Autowired
    private InvoiceHeaderMapper invoiceHeaderMapper;
    @Autowired
    private InvoiceTypeMapper invoiceTypeMapper;
    @Autowired
    private InvoiceconfigurationsMapper invoiceconfigurationsMapper;
    @Autowired
    private PrestorageMapper prestorageMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private InvoiceRecordsMapper invoiceRecordsMapper;
    @Autowired
    private BillingItemsMapper billingItemsMapper;
    private BillDetailsVos billDetailsVos = new BillDetailsVos();

    @Override
    public BillDetailsVos getBillListByAccountAndCustomerId(BillVerificationDto billVerificationDto, String account,boolean flag) {
        //根据客户id获取该客户所有的还欠费的账单
        List<Billes> billesList = baseMapper.getBillListByAccountAndCustomerId(billVerificationDto,account);
        if (billesList == null || billesList.isEmpty()) {
            return new BillDetailsVos(Collections.emptyList());
        }
        InvoiceHeaderes invoiceHeaderes = null;
        Invoiceconfigurations invoiceconfigurations = null;
        List<Invoicetypes> invoicetypesList = null;
        for (Billes billes : billesList) {
            List<PreStorages> preStoragesList = new ArrayList<>();
            //根据账单查询出该账单包含的所有资源
            List<Resourcees> resourceesList = resourceMapper.getResource(billVerificationDto,account, billes.getId());
            QueryWrapper<Invoicerecordes> invoicerecordsQueryWrapper = new QueryWrapper<>();
            invoicerecordsQueryWrapper.eq("billid", billes.getId()).eq("state",1);
            Invoicerecordes invoicerecordes = invoiceRecordsMapper.selectOne(invoicerecordsQueryWrapper);
            //根据该账单是否有开票记录来判断已开票还是未开票{0：未开票,1：已开票}
            if (invoicerecordes != null) {
                billes.setIsinvoiced(1);
            } else {
                billes.setIsinvoiced(0);
            }
            //根据客户id查询客户的开票配置
            QueryWrapper<Invoiceconfigurations> invoiceconfigurationQueryWrapper = new QueryWrapper<>();
            invoiceconfigurationQueryWrapper.eq("customerid", billVerificationDto.getCustomerid()).select("invocetypeid", "invoicingmethod");
            invoiceconfigurations = invoiceconfigurationsMapper.selectOne(invoiceconfigurationQueryWrapper);
            //开票方式为先款后票则返回相应的票信息，包括{该客户的开票抬头，系统所有的开票类型}
            if (invoiceconfigurations.getInvoicingmethod() == 0) {
                QueryWrapper<InvoiceHeaderes> invoiceHeaderQueryWrapper = new QueryWrapper<>();
                invoiceHeaderQueryWrapper.eq("customerid", billVerificationDto.getCustomerid()).eq("status", 1).eq("state",1).select("buyername", "taxpayernum", "address", "phone", "openingbank", "banknumber");
                invoiceHeaderes = invoiceHeaderMapper.selectOne(invoiceHeaderQueryWrapper);
                invoicetypesList = invoiceTypeMapper.selectList(null);
            }
            //根据资源和账单id查询该资源的所有账单详情
            for (Resourcees resourcees : resourceesList) {
                List<Billdetailes> billdetailesList = billDetailVerificationMapper.getBillDetailListByAccountAndCustomerId(billVerificationDto,account, resourcees.getId(), billes.getId());
                for (Billdetailes billdetail : billdetailesList) {
                    //查询该条账单详情对应的计费项目信息
                    QueryWrapper<BillingItemss> billingItemsQueryWrapper = new QueryWrapper<>();
                    billingItemsQueryWrapper.eq("id", billdetail.getBillingitemsid()).eq("state", 1).select("id", "specialName", "type", "specialdeposit", "deposittypeid");
                    BillingItemss billingItemss = billingItemsMapper.selectOne(billingItemsQueryWrapper);
                    QueryWrapper<PreStorages> preStorageQueryWrapper = new QueryWrapper<>();
                    preStorageQueryWrapper.eq("resourceid", resourcees.getId())
                            .eq("subject", billingItemss.getId())
                            .gt("afterchange", 0)
                            .select("id", "subject","afterchange").orderByDesc("operationtime");
                    //查出相同资源相同预收科目所有预存记录
                    List<PreStorages> getPrestorages = prestorageMapper.selectList(preStorageQueryWrapper);
                    PreStorages preStorages = null;
                    if(!getPrestorages.isEmpty()){
                        //获取相同资源相同预收科目最近的一条预存记录
                        preStorages = getPrestorages.get(0);
                    }
                    if(preStorages != null && preStorages.getAfterchange().compareTo(new BigDecimal(billdetail.getAccountsreceivable()))>0){
                        preStorages.setAfterchange(new BigDecimal(billdetail.getAccountsreceivable()));
                    }
                    if (preStorages != null) {
                        boolean exists = false;
                        // 遍历当前集合，检查是否存在相同的对象
                        for (PreStorages item : preStoragesList) {
                            if (item.getId().equals(preStorages.getId())) {
                                exists = true;
                                break;
                            }
                        }
                        // 如果集合中不存在相同的对象，则添加到集合中
                        if (!exists) {
                                preStoragesList.add(preStorages);
                        }
                    }
                }
                resourcees.setBilldetailesList(billdetailesList);
                resourcees.setPreStoragesList(preStoragesList);
            }
            billes.setResourceesList(resourceesList);
        }

        if(flag){
            billDetailsVos.setList(billesList);
        }
        billDetailsVos.setInvoiceHeaderes(invoiceHeaderes);
        billDetailsVos.setInvoicetypes(invoicetypesList);
        billDetailsVos.setInvoiceconfigurations(invoiceconfigurations);
        return billDetailsVos;
    }


//    @Override
//    public BillDetailsVos getBillListByAccountAndCustomerId(BillVerificationDto billVerificationDto) {
//        List<Billes> billList = baseMapper.getBillIdByCustomerIdAndAccount(billVerificationDto);
//        if (billList == null || billList.isEmpty()) {
//            return new BillDetailsVos(Collections.emptyList());
//        }
//
//        InvoiceHeaderes invoiceHeader = null;
//        Invoiceconfigurations invoiceconfiguration = null;
//        List<Invoicetypes> invoicetypeList = null;
//        List<PreStorages> preStorageList = null;
//
//        for (Billes bill : billList) {
//            List<Resourcees> resourceesList = resourceMapper.getMasterDataResource(billVerificationDto, bill.getId());
//
//            for (Resourcees resource : resourceesList) {
//                List<FeeClassifications> feeClassificationList = feeClassificationMapper.getFeeClassifications(billVerificationDto, resource.getId(), bill.getId());
//                Integer[] subjects = feeClassificationList.stream().map(FeeClassifications::getId).toArray(Integer[]::new);
//
//
//                List<Billdetailes> billdetailesList = billDetailVerificationMapper.getBillDetailListByAccountAndCustomerId(billVerificationDto, resource.getId(), bill.getId());
//                //TODO 判断账单详情中的费项对应资源的预存是否有专用，没有则返回通用预存
//                for (Billdetailes billdetails : billdetailesList) {
//                    if (billdetails.getFeeClassification().getId() == 8) {
//
//                    }
//                }
//                preStorageList = prestorageMapper.getPreStorages(billVerificationDto, resource.getId(), bill.getId(), subjects);
//                resource.setBilldetailesList(billdetailesList);
//                resource.setPreStoragesList(preStorageList);
//            }
//
//            bill.setResourceesList(resourceesList);
//
//            if (bill.getIsinvoiced() == 1) {
//                QueryWrapper<InvoiceHeaderes> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("customerid", billVerificationDto.getCustomerid())
//                        .select("buyername", "taxpayernum", "address", "phone", "openingbank", "banknumber");
//
//                QueryWrapper<Invoiceconfigurations> invoiceconfigurationQueryWrapper = new QueryWrapper<>();
//                invoiceconfigurationQueryWrapper.eq("customerid", billVerificationDto.getCustomerid())
//                        .select("invocetypeid", "invoicingmethod");
//
//                invoiceHeader = Optional.ofNullable(invoiceHeaderMapper.selectOne(queryWrapper)).orElse(null);
//                invoiceconfiguration = Optional.ofNullable(invoiceconfigurationMapper.selectOne(invoiceconfigurationQueryWrapper)).orElse(null);
//                invoicetypeList = Optional.ofNullable(invoiceTypeMapper.selectList(null)).orElse(Collections.emptyList());
//            }
//        }
//
//        if (invoiceHeader == null) {
//            return new BillDetailsVos(billList);
//        } else {
//            return new BillDetailsVos(billList, invoiceHeader, invoicetypeList, invoiceconfiguration);
//        }
//    }


}
